﻿using System;
using Contracts.General;
using Wombat.Core;
using Wombat.Core.Factories;
using Wombat.Core.Services;

namespace Wombat.WcfGate
{
    public class WcfFloatTagService : WcfTagService, IDataSubmissionService
    {
        private readonly ITagRpository _tagRpository;
        private readonly ITagStateService _tagStateService;
        private readonly ITagValueFactory _tagValueFactory;

        /// <summary>
        /// The cheating factory
        /// TODO: Get rid of this as soon as possible.
        /// </summary>
        public static Func<WcfFloatTagService> CheatingFactory;

        public delegate WcfFloatTagService Factory(IUniqueIdentifiable webServiceGateHost);

        public WcfFloatTagService(): base(null, null)
        {
            var temp = CheatingFactory();
            WebServiceGateHost = temp.WebServiceGateHost;
            ObservationManager = temp.ObservationManager;
            _tagRpository = temp._tagRpository;
            _tagStateService = temp._tagStateService;
            _tagValueFactory = temp._tagValueFactory;
        }

        public WcfFloatTagService(IUniqueIdentifiable webServiceGateHost, IObservationManager observationManager, ITagRpository tagRpository, ITagStateService tagStateService
            , ITagValueFactory tagValueFactory) : base(observationManager, webServiceGateHost)
        {
            _tagRpository = tagRpository;
            _tagStateService = tagStateService;
            _tagValueFactory = tagValueFactory;
        }

        public void SubmitDataDouble(long tagId, DateTime time, double? data)
        {
            if (time.Kind == DateTimeKind.Unspecified)
                time = DateTime.SpecifyKind(time, DateTimeKind.Utc);
            var tag = _tagRpository.Get(tagId);

            var tagValue = _tagValueFactory.CreateNew(tag.UniqueId, time, data);
            _tagStateService.SetTagValue(tagValue.TagId, tagValue.Time, data);
            ObservationManager.OnNext(WebServiceGateHost, (ITagValue)tagValue);
        }
    }
}